const http = require('http')
const ffmpeg = require('fluent-ffmpeg')
const { Server } = require('socket.io')
const path = require('path')
const url = require('url')
const videoPath = encodeURI(path.resolve('D:\\迅雷下载\\阳光电影www.ygdy8.com.姜子牙.HD.1080p.国语中字.mkv'))
var server = null
var ffstream = null
var command = null
var socketio = null
export default function ffmpegApp() {
    return new Promise((resolve, reject) => {
        server = http
            .createServer((req, res) => {
                if (req.url == '/') {
                    res.writeHead(200, { 'Content-Type': 'text/html' })
                    // console.log(videoPath)
                    res.end(`
                    <video width="500" preload controls="controls" src="/play?path=${videoPath}&startTime=0" type='video/mp4'>
                    </video>
                `)
                } else if (req.url.indexOf('/play') != -1) {
                    createSocket()

                    // 获取post参数
                    // let arr = []
                    // // 通过req监听data事件，buffer就是每次接收到的一点数据
                    // req.on('data', (buffer) => {
                    //     arr.push(buffer)
                    // })
                    // // 在所有的数据接收完毕之后（end事件）需要将所有的数据碎片做一个整合
                    // req.on('end', () => {
                    //     // 合并所有的buffer碎片
                    //     const buffer = Buffer.concat(arr)
                    //     // 将buffer转化成可读性的内容
                    //     const params = getPostData(buffer)
                    //     console.log(params)
                    //     ffstream = ffmpegFunc(params.path)
                    //     ffstream.pipe(res)
                    // })

                    // 获取get参数
                    const { query } = url.parse(req.url, true)
                    const { path, startTime } = query
                    const parmas = { path: decodeURI(path), startTime }
                    ffstream = ffmpegFunc(parmas)
                    ffstream.pipe(res)
                } else if (req.url.indexOf('/test') != -1) {
                    res.end('test')
                }
            })
            .listen(3667, () => {
                resolve(server)
                console.log('listen port 3667')
            })
    })
}
function createSocket() {
    const io = new Server(server, {
        cors: { origin: '*' },
    })
    io.on('connection', (socket) => {
        console.log('socket connected: ', socket.id)
        socketio = socket
        if (ffstream && socket.connected) {
            if (global.videoInfo) {
                socket.emit('videoInfo', global.videoInfo)
            }
            // ffstream.on('data', function(chunk) {
            //     // console.log(chunk)
            //     // console.log('ffmpeg just wrote ' + chunk.length + ' bytes')
            //     // socket.emit('videoData', { speed: chunk.length / 1024 })
            // })
        }
        socket.on('disconnect', () => {
            console.log('socket disconnected: ', socket.id)
        })
    })
}
function getPostData(buffer) {
    let data = decodeURIComponent(buffer.toString()).split('&')
    let params = {}
    for (const v of data) {
        let arr = v.split('=')
        params[arr[0]] = arr[1]
    }
    return params
}
function ffmpegFunc({ path, startTime = 0 }) {
    if (command) {
        command.kill()
    }
    command = ffmpeg(path)
        // .videoCodec('libx264')
        // .audioCodec('libmp3lame')
        // .size('320x240')
        .format('mp4')
        .seekInput(startTime)
        .outputOptions('-movflags', 'frag_keyframe+empty_moov')
        .on('codecData', function(data) {
            // console.log(data)
            global.videoInfo = JSON.stringify(data)
        })
        // .on('stderr', function(stderrLine) {
        //     console.log('Stderr output: ' + stderrLine)
        // })
        .on('progress', (val) => {
            if (socketio) {
                socketio.emit('videoData', val)
            }
        })
        .on('error', function(err) {
            // console.log('An error occurred: ' + err.message)
        })
        .on('end', function() {
            console.log('Processing finished !')
        })
    return command.pipe()
}

// ffmpegApp()
